<template>
  <div class="app-container">
    <el-card>
      <!-- 筛选区域 -->
      <el-form :model="filterForm" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="药剂名称">
              <el-input v-model="filterForm.name" placeholder="输入药剂名称" clearable>
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="规格型号">
              <el-input v-model="filterForm.spec" placeholder="输入规格型号" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="生产厂家">
              <el-input v-model="filterForm.manufacturer" placeholder="输入生产厂家" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="库存状态">
              <el-select v-model="filterForm.stockStatus" placeholder="选择库存状态" clearable style="width: 100%">
                <el-option label="充足" value="normal" />
                <el-option label="预警" value="warning" />
                <el-option label="不足" value="danger" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="时间范围">
              <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-button type="primary" :icon="Search" @click="handleQuery">
              查询
            </el-button>
            <el-button :icon="Refresh" @click="handleReset">
              重置
            </el-button>
            <el-button :icon="Download" @click="handleExport">
              导出Excel
            </el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 操作按钮 -->
      <div>
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          新增
        </el-button>
        <el-button :icon="Box" @click="handleStockIn">
          入库
        </el-button>
        <el-button :icon="Truck" @click="handleStockOut">
          出库
        </el-button>
        <el-button :icon="Edit" @click="handleUsageRegister">
          使用登记
        </el-button>
      </div>
      <!-- 药剂表格 -->
      <el-table class="mt-2" :data="medicineList" border style="width: 100%">
        <el-table-column prop="name" label="药品名称" align="center" />
        <el-table-column prop="spec" label="规格型号" align="center" />
        <el-table-column prop="manufacturer" label="生产厂家" align="center" />
        <el-table-column prop="batchNo" label="批次号" align="center" />
        <el-table-column prop="currentStock" label="当前库存" align="center">
          <template #default="{ row }">
            <el-tag :type="getStockTagType(row)">
              {{ row.currentStock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="计量单位" align="center" />
        <el-table-column prop="warningValue" label="库存预警值" align="center" />
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleDetail(row)">
              详情
            </el-button>
            <el-button type="text" size="small" @click="handleDelete(row)" style="color: #f56c6c">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>


    <!-- 添加 -->
    <el-dialog title="新增药剂" v-model="medicineFormVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="medicineFormRef" :model="medicineForm" :rules="formRules" label-width="100px" label-position="left">
        <!-- 药剂名称 -->
        <el-form-item label="药剂名称" prop="name">
          <el-input v-model="medicineForm.name" placeholder="输入药剂名称" clearable />
        </el-form-item>

        <!-- 规格型号 -->
        <el-form-item label="规格型号" prop="spec">
          <el-input v-model="medicineForm.spec" placeholder="输入规格型号" clearable />
        </el-form-item>

        <!-- 生产厂家 -->
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="medicineForm.manufacturer" placeholder="输入生产厂家" clearable />
        </el-form-item>

        <!-- 计量单位和库存预警值 -->
        <el-form-item label="计量单位" prop="unit">
          <el-select v-model="medicineForm.unit" placeholder="请选择计量单位" style="width: 100%">
            <el-option label="千克" value="kg" />
            <el-option label="升" value="L" />
            <el-option label="克" value="g" />
            <el-option label="毫升" value="ml" />
            <el-option label="吨" value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存预警值" prop="warningValue">
          <el-input-number v-model="medicineForm.warningValue" :min="1" :max="9999" controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <!-- 药剂图片 -->
        <el-form-item label="药剂图片">
          <UploadFile />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="medicineFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(medicineFormRef)">
            确认新增
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 入库 -->
    <el-dialog title="药剂入库" v-model="warehouseVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="stockInFormRef" :model="stockInForm" :rules="warehouseFormRules" label-width="100px"
        label-position="left">
        <!-- 药剂信息 -->
        <el-form-item label="药剂名称" prop="medicineId">
          <el-select v-model="stockInForm.medicineId" placeholder="选择药剂" filterable style="width: 100%">
            <el-option v-for="item in medicineList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="入库数量" prop="quantity">
          <el-input-number v-model="stockInForm.quantity" :min="1" :max="9999" controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="stockInForm.batchNumber" placeholder="输入批次号" clearable />
        </el-form-item>

        <!-- 生产信息 -->
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker v-model="stockInForm.productionDate" type="date" placeholder="选择生产日期" style="width: 100%"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="保质期(月)" prop="shelfLife">
          <el-input-number v-model="stockInForm.shelfLife" :min="1" :max="120" controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="stockInForm.supplier" placeholder="输入供应商" clearable />
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input v-model="stockInForm.remark" type="textarea" :rows="3" placeholder="输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warehouseVisible = false">取消</el-button>
          <el-button type="primary" @click="warehouseSubmitForm(stockInFormRef)">
            确认入库
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!--药剂出库  -->
    <el-dialog title="药剂出库" v-model="outVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="stockInFormRef" :model="outForm" label-width="100px" label-position="left">
        <el-form-item label="出库数量" required>
          <el-input-number v-model="outForm.number" :min="1" :max="9999" controls-position="right"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="outVisible = false">取消</el-button>
          <el-button type="primary" @click="outSubmitForm(stockInFormRef)">
            确认出库
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!--使用登记  -->
    <el-dialog title="药剂使用登记" v-model="useVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="stockInFormRef" :model="useForm" label-width="100px" label-position="left">
        <el-form-item label="使用数量" required>
          <el-input-number v-model="useForm.number" :min="1" :max="9999" controls-position="right"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="useVisible = false">取消</el-button>
          <el-button type="primary" @click="useSubmitForm(stockInFormRef)">
            确认使用
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 药剂详情 -->
    <el-dialog title="药剂详情" v-model="pharmacyVisible" width="900px" top="5vh" :close-on-click-modal="false">
      <el-tabs v-model="activeTab" type="card">
        <!-- 基本信息标签页 -->

        <el-tab-pane label="基本信息" name="basic">

          <el-descriptions border column="1" label-width="200px">
            <el-descriptions-item :rowspan="1"label="Photo">
              <el-image style="width: 100px; height: 100px"
                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
            </el-descriptions-item>
            <el-descriptions-item label="药剂名称">
              <span class="highlight-text">{{ medicineInfo.name }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="规格型号">
              {{ medicineInfo.spec }}
            </el-descriptions-item>
            <el-descriptions-item label="生产厂家">
              {{ medicineInfo.manufacturer }}
            </el-descriptions-item>
            <el-descriptions-item label="批次号">
              {{ medicineInfo.batchNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="当前库存">
              <el-tag :type="getStockTagType(medicineInfo)">
                {{ medicineInfo.currentStock }} {{ medicineInfo.unit }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="库存预警值">
              {{ medicineInfo.warningValue }} {{ medicineInfo.unit }}
            </el-descriptions-item>
            <el-descriptions-item label="入库时间">
              {{ medicineInfo.stockInTime }}
            </el-descriptions-item>
            <el-descriptions-item label="保质期">
              {{ medicineInfo.expiryDate }}
              <el-tag v-if="isExpiringSoon" type="warning" size="small" style="margin-left: 8px">
                即将过期
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <!-- 出入库记录标签页 -->
        <el-tab-pane label="出入库记录" name="stock">
          <el-table :data="stockRecords" border style="width: 100%">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.type === '入库' ? 'success' : 'danger'">
                  {{ row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="120" />
            <el-table-column prop="operator" label="操作人" width="120" />
            <el-table-column prop="batchNumber" label="批次号" width="150" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-tab-pane>

        <!-- 使用记录标签页 -->
        <el-tab-pane label="使用记录" name="usage">
          <el-table :data="usageRecords" border style="width: 100%">
            <el-table-column prop="date" label="使用日期" width="120" />
            <el-table-column prop="quantity" label="使用量" width="120" />
            <el-table-column prop="operator" label="操作人" width="120" />
            <el-table-column prop="process" label="处理工艺" width="150" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pharmacyVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import UploadFile from '@/components/UploadFile';


// 筛选表单
const filterForm = reactive({
  name: '',
  spec: '',
  manufacturer: '',
  dateRange: [],
  stockStatus: ''
})

// 药剂列表数据
const medicineList = ref([
  {
    id: 1,
    name: '聚合氯化铝',
    spec: 'PAC-30',
    manufacturer: '上海石化股份有限公司',
    batchNo: 'BJ20230501',
    currentStock: 320,
    unit: 'kg',
    warningValue: 500
  },
  {
    id: 2,
    name: '聚丙烯酰胺',
    spec: 'PAM-AN910',
    manufacturer: '上海石化股份有限公司',
    batchNo: 'SH20230428',
    currentStock: 320,
    unit: 'kg',
    warningValue: 500
  },
  {
    id: 3,
    name: '次氯酸钠',
    spec: 'NaClO-10%',
    manufacturer: '天津大冶化工有限公司',
    batchNo: 'TJ20230612',
    currentStock: 2800,
    unit: 'L',
    warningValue: 1000
  },
  {
    id: 4,
    name: '活性炭',
    spec: 'AC-200',
    manufacturer: '山西新华浩特有限公司',
    batchNo: 'SX20230522',
    currentStock: 180,
    unit: 'kg',
    warningValue: 200
  },
  {
    id: 5,
    name: '氢氧化钠',
    spec: 'NaOH-30%',
    manufacturer: '南京化学工业有限公司',
    batchNo: 'NJ20230605',
    currentStock: 420,
    unit: 'kg',
    warningValue: 300
  }
])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

const medicineFormRef = ref()
const medicineFormVisible = ref(false);
// 表单数据
const medicineForm = reactive({
  name: '',
  spec: '',
  manufacturer: '',
  unit: 'kg',
  warningValue: 100,
  imageUrl: ''
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入药剂名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  spec: [
    { required: true, message: '请输入规格型号', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  manufacturer: [
    { required: true, message: '请输入生产厂家', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请选择计量单位', trigger: 'change' }
  ],
  warningValue: [
    { required: true, message: '请输入库存预警值', trigger: 'blur' },
    { type: 'number', min: 1, message: '预警值必须大于0', trigger: 'blur' }
  ]
})


const submitForm = (formRef) => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 提交表单逻辑
      console.log('Form is valid:', medicineForm);
      medicineFormVisible.value = false;
    } else {
      console.log('Form is invalid');
    }
  })
}


// 入库
const warehouseVisible = ref(false);

const stockInFormRef = ref()


// 表单数据
const stockInForm = reactive({
  medicineId: '',
  quantity: 1,
  batchNumber: '',
  productionDate: '',
  shelfLife: 12,
  supplier: '',
  remark: ''
})

// 表单验证规则
const warehouseFormRules = reactive({
  medicineId: [
    { required: true, message: '请选择药剂', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入入库数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  batchNumber: [
    { required: true, message: '请输入批次号', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  productionDate: [
    { required: true, message: '请选择生产日期', trigger: 'change' }
  ],
  shelfLife: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
    { type: 'number', min: 1, message: '保质期必须大于0', trigger: 'blur' }
  ],
  supplier: [
    { required: true, message: '请输入供应商', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur' }
  ]
})


// 表单提交
const warehouseSubmitForm = async () => {
  stockInFormRef.value.validate(valid => {
    if (valid) {
      // 提交表单逻辑
      console.log('Form is valid:', stockInForm);
      warehouseVisible.value = false;
    } else {
      console.log('Form is invalid');
    }
  })
}


// 出库
const outVisible = ref(false);
const outForm = {
  number: 10
}
const outSubmitForm = () => {
  console.log('出库操作')
  console.log(outForm.value);
}


// 使用 
const useVisible = ref(false);
const useForm = reactive({
  number: 10
})
const useSubmitForm = () => {
  console.log('使用登记');
  useVisible.value = false;
}


const pharmacyVisible = ref(false);
const activeTab = ref('basic');

// 药剂基本信息
const medicineInfo = ref({
  name: '聚合氯化铝',
  spec: 'PAC-30',
  manufacturer: '北京蓝星化工有限公司',
  batchNumber: 'BJ20230501',
  currentStock: 1250,
  unit: 'kg',
  warningValue: 500,
  stockInTime: '2023-05-15',
  expiryDate: '2024-05-14'
})

// 出入库记录
const stockRecords = ref([
  {
    date: '2023-05-15',
    type: '入库',
    quantity: '1500 kg',
    operator: '张伟',
    batchNumber: 'BJ20230501',
    remark: '新采购批次'
  },
  {
    date: '2023-06-10',
    type: '出库',
    quantity: '250 kg',
    operator: '李娜',
    batchNumber: 'BJ20230501',
    remark: '常规使用'
  },
  {
    date: '2023-06-20',
    type: '出库',
    quantity: '200 kg',
    operator: '王强',
    batchNumber: 'BJ20230501',
    remark: '应急处理'
  }
])

// 使用记录
const usageRecords = ref([
  {
    date: '2023-06-10',
    quantity: '250 kg',
    operator: '李娜',
    process: '混凝沉淀',
    remark: '常规投加'
  },
  {
    date: '2023-06-20',
    quantity: '200 kg',
    operator: '王强',
    process: '应急处理',
    remark: '水质异常处理'
  }
])

// 计算是否即将过期（30天内）
const isExpiringSoon = computed(() => {
  const expiryDate = new Date(medicineInfo.value.expiryDate)
  const today = new Date()
  const diffTime = expiryDate - today
  const diffDays = diffTime / (1000 * 60 * 60 * 24)
  return diffDays > 0 && diffDays <= 30
})

// 获取库存标签类型
const getStockTagType = (medicine) => {
  if (medicine.currentStock < medicine.warningValue * 0.3) {
    return 'danger'
  } else if (medicine.currentStock < medicine.warningValue) {
    return 'warning'
  }
  return 'success'
}
// 操作方法
const handleQuery = () => {
  console.log('查询条件:', filterForm)
  // 实际项目中这里调用API查询数据
}

const handleReset = () => {
  Object.assign(filterForm, {
    name: '',
    spec: '',
    manufacturer: '',
    dateRange: [],
    stockStatus: ''
  })
}

const handleExport = () => {
  console.log('导出Excel')
}

const handleAdd = () => {
  console.log('新增药剂')
  medicineFormVisible.value = true;
}

const handleStockIn = () => {
  console.log('入库操作')
  warehouseVisible.value = true;
}

const handleStockOut = () => {
  console.log('出库操作')
  outVisible.value = true;
}

const handleUsageRegister = () => {
  console.log('使用登记')
  useVisible.value = true;
}

const handleDetail = (row) => {
  console.log('查看详情:', row)
  pharmacyVisible.value = true;
}

const handleDelete = (row) => {
  console.log('删除药剂:', row)
  // 实际项目中这里调用API删除数据
}

// 分页方法
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`)
  pagination.pageSize = val
}

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`)
  pagination.currentPage = val
}
</script>

<style scoped></style>